define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');


    var omFirstTime = true, omManagerFirstTime = true, cityFirstTime = true, areaFirstTime = true;
    var tables = {};
    var newUser = {
        areas: {
            "1": {name: "华东", cities: [], orderCnt: 0},
            "2": {name: "华南", cities: [], orderCnt: 0},
            "3": {name: "华北", cities: [], orderCnt: 0},
            "4": {name: "华中", cities: [], orderCnt: 0},
            "5": {name: "西南", cities: [], orderCnt: 0},
            "6": {name: "东北", cities: [], orderCnt: 0}
        },
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "OM拉新数据查询") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initCity();
            this.initTable("#om_table", "cityXiaoerOrders", [
                {
                    "sTitle": "城市",
                    "bSortable": false
                },
                {
                    "sTitle": "小二昵称",
                    "bSortable": false
                },
                {
                    "sTitle": "小二号码",
                    "bSortable": false
                },
                {
                    "sTitle": "拉新数量",
                    "bSortable": true
                }

            ], omFirstTime);
            this.initTable("#om_manager_table", "cityManagerOrders", [
                {
                    "sTitle": "城市",
                    "bSortable": false
                },
                {
                    "sTitle": "OM主管昵称",
                    "bSortable": false
                },
                {
                    "sTitle": "OM主管号码",
                    "bSortable": false
                },
                {
                    "sTitle": "拉新数量",
                    "bSortable": true
                }

            ], omManagerFirstTime);
            this.initTable("#city_table", "cityManagerOrdersGroupByCity", [
                {
                    "sTitle": "城市",
                    "bSortable": false
                },
                {
                    "sTitle": "拉新数量",
                    "bSortable": true
                }

            ], cityFirstTime);
            this.initTable("#area_table", "cityManagerOrdersGroupByCity", [
                {
                    "sTitle": "城市",
                    "bSortable": false
                },
                {
                    "sTitle": "拉新数量",
                    "bSortable": true
                }

            ], areaFirstTime);
            this.initDatetimepicker();
            this.initValidator();
            this.bindEvent();
        },
        /**
         * 执行查询操作.
         */
        doSearch: function () {
            var self = this;
            $("#query_form").data('bootstrapValidator').resetForm();
            $("#query_form").data('bootstrapValidator').validate();
            if ($("#query_form").data('bootstrapValidator').isValid()) {
                $('#area_table').DataTable().ajax.reload();
                $('#city_table').DataTable().ajax.reload();
                $('#om_manager_table').DataTable().ajax.reload();
                $('#om_table').DataTable().ajax.reload();
            }

        },
        /**
         * 城市初始化
         */
        initCity: function () {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl('/shop/city/queryOpenCity'),
                "dataType": "json",
                contentType: "application/json",
                data: JSON.stringify({}),
                "success": function (req) {
                    if (req.status) {
                        var allCities = "";
                        $.each(req.entry, function (index, item) {
                            allCities += item.city + ",";
                            //$("#cities").append("<option value='" + item.city + "'>" + item.city + "</option>");
                            if (self.areas[item.araeId]) {
                                self.areas[item.araeId].cities.push(item.city)
                            }
                        });
                        allCities = allCities.substring(0, allCities.length - 1);
                        $("#cities").append("<option value='" + allCities + "' selected>全国</option>");
                        $.each(self.areas, function (key, area) {
                            $("#cities").append("<option value='" + area.cities.toString() + "'>" + area.name + "</option>");
                        });
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         *
         * @param tableId
         * @param serviceName
         * @param aoColumns
         * @param firstTime
         */
        initTable: function (tableId, serviceName, aoColumns, firstTime) {
            var self = this;
            var _table = $(tableId).dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": false,  //是否显示分页
                "bLengthChange": false,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": true, //是否支持排序功能
                "bInfo": true, //显示表格信息
                "bAutoWidth": true,  //自适应宽度
                "bServerSide": false,//开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/iris-api/service'),
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    if (firstTime) {
                        firstTime = false;
                        return;
                    }
                    if (!$("#start").val() || !$("#start").val()) {
                        return;
                    }
                    var _data = {};
                    $($("#query_form").serializeArray()).each(function () {
                        _data[this.name] = this.value;
                    });
                    if (cities) {
                        var _cities = _data.cities.split(",");
                        _data.city_name = [];
                        $.each(_cities, function (_key, _city) {
                            _data.city_name.push(_city);
                        });
                    }
                    var param = {};
                    param.param = _data;
                    param.serviceName = serviceName;
                    CRM.request({
                        "type": 'POST',
                        "url": sSource,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": JSON.stringify(param),
                        "success": function (req) {
                            if (req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = req.entry.result.length;
                                    resultData.iTotalRecords = req.entry.result.length;
                                    if (tableId == "#area_table") {
                                        $.each(self.areas, function (key, area) {
                                            area.orderCnt = 0;
                                        });
                                    }
                                    for (var length in req.entry.result) {
                                        if (tableId == "#om_table") {
                                            resultData.aaData.push([
                                                req.entry.result[length].city_name,
                                                req.entry.result[length].xiaoer_nick,
                                                req.entry.result[length].xiaoer_mobile,
                                                req.entry.result[length].order_cnt]);

                                        } else if (tableId == "#om_manager_table") {
                                            resultData.aaData.push([
                                                req.entry.result[length].city_name,
                                                req.entry.result[length].manager_nick,
                                                req.entry.result[length].manager_mobile,
                                                req.entry.result[length].order_cnt]);
                                        } else if (tableId == "#city_table") {
                                            resultData.aaData.push([
                                                req.entry.result[length].city_name,
                                                req.entry.result[length].order_cnt]);
                                        } else if (tableId == "#area_table") {
                                            $.each(self.areas, function (key, area) {
                                                $.each(area.cities, function (index, city) {
                                                    if (city == req.entry.result[length].city_name) {
                                                        area.orderCnt += req.entry.result[length].order_cnt;
                                                    }
                                                });
                                            });
                                        }
                                    }
                                    if (tableId == "#area_table") {
                                        $.each(self.areas, function (key, area) {
                                            if ($("#cities").val().indexOf(area.cities.toString()) != -1 && area.cities.length > 0) {
                                                resultData.aaData.push([area.name, area.orderCnt]);
                                            }

                                        });
                                    }
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                },
                "aaSorting": [],  //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": aoColumns, //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "full_numbers" //分页，一共两种样式，full_numbers和two_button(默认)

            });
            tables[tableId] = _table;
        },
        /**
         * 初始化日期控件
         */
        initDatetimepicker: function () {
            $(".form_time").datetimepicker({
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 1,
                minView: 0,
                maxView: 1,
                forceParse: 0
            });
            $('.form_date').datetimepicker({
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
            });
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#query_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    start: {
                        message: '开始时间输入错误',
                        validators: {
                            notEmpty: {
                                message: '开始时间不能为空'
                            },
                            callback: {
                                message: '时间跨度不能超过7天',
                                callback: function (value, validator) {
                                    var gmtCreateStart = +new Date($("#start").val()),
                                        gmtCreateEnd = +new Date($("#end").val());
                                    if (gmtCreateEnd - gmtCreateStart > 604800000) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                }
                            }
                        }
                    },
                    end: {
                        message: '结束时间输入错误',
                        validators: {
                            notEmpty: {
                                message: '结束时间不能为空'
                            },
                            callback: {
                                message: '时间跨度不能超过7天',
                                callback: function (value, validator) {
                                    var gmtCreateStart = +new Date($("#start").val()),
                                        gmtCreateEnd = +new Date($("#end").val());
                                    if (gmtCreateEnd - gmtCreateStart > 604800000) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            });

        },
        bindEvent: function () {
            var self = this;
            $("#search_btn").on('click', function () {
                self.doSearch();
            });
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                tables["#" + $(e.target).attr("aria-controls") + "_table"].fnAdjustColumnSizing();
            })

        }
    };

    window.doSearch = $.proxy(newUser.doSearch, newUser);

    newUser.init();
});